<template>
  <div>
    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
      验证码登录
    </van-divider>
    <div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="phone"
          name="手机号"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '请填写手机号' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号格式有误' },
          ]"
        />
        <van-field
          v-model="sms"
          center
          clearable
          label="短信验证码"
          placeholder="请输入短信验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              :disabled="isClick"
              type="primary"
              @click.stop="sendCode()"
            >
              {{ time }}
            </van-button>
          </template>
        </van-field>
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit">登录</van-button>
          <van-button round block type="info" @click.stop="login()" class="login">
            密码登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import url from "../tools/url";
export default {
  name: "byCode",
  data() {
    return {
      phone: "",
      sms: "",
      isClick: false,
      time: "发送验证码",
    };
  },
  methods: {
    login() {
      this.$router.push("/Login");
    },
    onSubmit() {
      var str = `phone=${this.phone}&code=${this.sms}`;
      this.axios.post(url.LOGIN, str).then((res) => {
        if (res.data.code == 200) {
          sessionStorage.setItem("token", res.data.data.token);
          this.$store.commit("saveInfo", res.data.data);
          this.$router.push("/HelloWorld");
        } else {
          Toast(res.data.message);
        }
      });
    },
    sendCode() {
      if (/^1[3456789]\d{9}$/.test(this.phone)) {
        this.isClick = true;
        var s = 5;
        var timer = setInterval(() => {
          this.time = s + "秒";

          if (s <= 0) {
            clearInterval(timer);
            this.isClick = false;
            this.time = "重新发送";
          }
          s--;
        }, 1000);
        this.axios.get(url.GET_CODE + "?phone=" + this.phone).then((res) => {
          console.log(res);
          this.sms = res.data.data;
        });
      } else {
        Toast("请输入正确的手机号格式");
      }
    },
  },
};
</script>

<style scoped>
.login {
  margin-top: 10px;
}
</style>
